var config = require('../../config.js')
var http = require('../../utils/httpHelper.js')
Page({
  data: {
    userInfo: {},
  },
  onShow: function () {
    var that = this
    let userInfo = wx.getStorageSync('user');
    var allAddress = wx.getStorageSync('address');
    var address = '';
    that.setData({
      userInfo:userInfo
    });
    for(var i=0;i<allAddress.length;i++){
      if( allAddress[i].checked){
        address = allAddress[i];
        break;
      }
    }
    if(address == '' && allAddress.length > 0){
      address = allAddress[0];
    }
    that.setData({
      address:address
    });
  },
  username:function (){
    wx.navigateTo({ url: '/pages/userdata/username/index'});
  },
  sex:function (){
    wx.navigateTo({ url: '/pages/userdata/sex/index'});
  },
  address:function (){
    wx.navigateTo({ url: '/pages/address/index'});
  },
  onChooseAvatar:function(e) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    if (e.detail.avatarUrl!=undefined&&e.detail.avatarUrl!=null&&e.detail.avatarUrl!=''&&
      userInfo.userId!=undefined&&userInfo.userId!=null&&userInfo.userId!='') {
      http.httpUpload(config.clubApi.putAvatar,e.detail.avatarUrl,{
        'userId':userInfo.userId
      },function (res){
        if (res.code == '200') {
          userInfo.avatar = res.data;
          wx.setStorageSync('user', userInfo);
          that.setData({userInfo:userInfo});
          util.showSuccess('设置成功!', config.showSuccessTime, () => {
            that.onShow();
          })
        }
      });
    }else if (userInfo.userId!=undefined&&userInfo.userId!=null&&userInfo.userId!='') {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          that.updateUseravatar(userInfo.userId, res.tempFilePaths);
        }
      })
    }
  },
  updateUseravatar:function (userId, userAvatar) {
    var that = this;
    let userInfo = wx.getStorageSync('user');
    wx.uploadFile({
      url: config.clubApi.putAvatar,
      filePath: userAvatar,
      method: 'POST',
      name: 'file',
      header: {  
        'Content-Type': 'multipart/form-data'
      },
      formData: {
        'userId': userId
      },
      success (res){
        if (res.statusCode===200) {
          let json = JSON.parse(res.data);
          userInfo.avatar = json.data;
          wx.setStorageSync('user', userInfo);
          that.setData({userInfo:userInfo});
          util.showSuccess('设置成功!', config.showSuccessTime, () => {
            that.onShow();
          })
        }
      }
    })
  }
})